<?php
/**
 * 泉鸣短信接口SDK
 * author:安然_(https://www.geet.cn)
 * update: 2022-9-18(修复)
 * PHP版本要求：php5.6及以上版本（其他版本请自行修改适配）
 * 官网：dev.quanmwl.com
 */

// 【示例代码】（修改29-30行的配置后可解除注释进行测试）
// $sms = new QuanmSmsSDK();
// $result = $sms->sendSms('15666666666', ['code' => '1234']);
// var_dump($result);

class QuanmSmsSDK
{
    //泉明开放平台openId
    private $appId;
    //泉明开放平台apiKey
    private $apiKey;
    //泉明开放平台接口地址
    private $apiUrl;
    //泉明开放平台短信模板ID
    private $templateId;

    public function __construct()
    {

        $this->appId  = '';  // 从平台控制面板获取
        $this->apiKey  = '';  // 从平台控制面板-能力管理-短信接口(SMS)页面开通后获取
        $this->apiUrl   = 'http://dev.quanmwl.com/'; // 接口网关地址(host)一般不需要修改，已支持https，如有需要请自行修改
        $this->templateId  = '0';  //短信模板ID，从平台申请,SDK默认使用0号公用模板测试
    }

    private $stateCode = [
        200 => '短信发送成功',
        201 => '表单信息或接口信息有误',
        202 => '信息重复',
        203 => '服务器异常，请稍后重拾',
        204 => '找不到数据',
        205 => '本次请求不安全',
        206 => '接口版本过低',
        207 => '余额不足',
        208 => '验签失败',
        209 => '功能被禁用',
        210 => '账户被禁用',
        211 => '参数过长',
        212 => '权限不足',
        213 => '参数调用状态异常',
        214 => '版本过高',
        215 => '内容受限',
        216 => '内容违规',
        '???' => '严重未知错误，请联系服务提供商'
    ];

    public function sendSms($tel, $args = []): array
    {
        $data = [
            'openID' => $this->appId,
            'tel' => $tel,
            'model_args' => json_encode($args),
            'sign' => $this->generateSign($tel,json_encode($args)),
            'model_id' => $this->templateId

        ];
        return $this->curlPost('v1/sms', $data);
    }

    private function generateSign($mobile,$model_args)
    {
        return md5($this->appId.$this->apiKey.$mobile.$this->templateId.$model_args);
    }

    private function curlPost($path, $body)
    {
        $curl = curl_init();
        $resquest_api = $this->apiUrl . $path;
        curl_setopt($curl, CURLOPT_URL, $resquest_api);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_NOBODY, FALSE);
        $response = curl_exec($curl);
        curl_close($curl);
        $response = json_decode($response, true);
        if (array_key_exists($response['state'], $this->stateCode)) {
            return ['code' => $response['state'], 'msg' => $response['mess']];
        } else {
            return ['code' => '-1', 'msg' => '请求结果错误，请联系开发人员核实'];
        }
    }

}